import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Article from 'src/entities/article.entity';
import { Repository } from 'typeorm';
import { CreateArticleDto } from './article.dto';
import User from 'src/entities/user.entity';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article) private articleRepository: Repository<Article>,
    @InjectRepository(User) private userRepository: Repository<User>,
  ) {}

  // 发布文章
  async create(createArticleDto: CreateArticleDto) {
    await this.articleRepository.save(createArticleDto);
  }

  // 查询文章
  async find() {
    const articleList = await this.articleRepository.find();

    const articlePromise = articleList.map(async (item) => {
      const user = await this.userRepository.findOne({
        where: { id: item.userId },
        select: ['avatar', 'nickname'],
      });
      return { ...item, ...user };
    });

    return await Promise.all(articlePromise);
  }

  // 获取文章详细
  async findOne(id: number) {
    return await this.articleRepository.findOne({ where: { id } });
  }
}
